package io.renren.modules.h5.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.interceptor.GlobalConstant;
import io.renren.common.page.PageData;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.Result;
import io.renren.modules.nuaa.dto.*;
import io.renren.modules.nuaa.entity.TAboutEntity;
import io.renren.modules.nuaa.entity.TNewsEntity;
import io.renren.modules.nuaa.entity.TSignupRecordEntity;
import io.renren.modules.nuaa.entity.TUserEntity;
import io.renren.modules.nuaa.service.*;
import io.renren.modules.skate.dto.*;
import io.renren.modules.skate.entity.FAthleteEntity;
import io.renren.modules.skate.entity.FCertificateEntity;
import io.renren.modules.skate.entity.FNewsEntity;
import io.renren.modules.skate.service.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@RestController
@Controller
@RequestMapping("/h5")
public class IndexController {

    @Autowired
    private TSignupRecordService tSignupRecordService;
    @Autowired
    private TQuestionService tQuestionService;
    @Autowired
    private TQuestionItemService tQuestionItemService;
    @Autowired
    private TQuestionOptionsService tQuestionOptionsService;
    @Autowired
    private TUserService tUserService;
    @Autowired
    private TCertificateService tCertificateService;
    @Autowired
    private TAboutService tAboutService;

    //*********************************************

    @Autowired
    private FClassifyService fClassifyService;
    @Autowired
    private FNewsService fNewsService;
    @Autowired
    private FMemberUnitService fMemberUnitService;
    @Autowired
    private FCertificateService fCertificateService;
    @Autowired
    private FCompetitionService fCompetitionService;
    @Autowired
    private FAthleteService fAthleteService;
    @Autowired
    private FClubService clubService;



    @Value("${domain}")
    private String domain = "http://localhost/img/";
    @Value("${picDir}")
    private String picDir = "/Users/wanghucheng/Downloads/picture/";

    @RequestMapping(value = "/{url}", method = RequestMethod.GET)
    public String show(@PathVariable("url") String url, HttpServletRequest request) {
        String backUrl = (String)request.getParameter("backUrl");
        request.setAttribute("backUrl", backUrl);
        if("about".equals(url)) {
            TAboutEntity about = tAboutService.selectById(1);
            request.setAttribute("about", about);
        }else if("news-list".equals(url)){
            String id = request.getParameter("id");
            String site = request.getParameter("site");
            Integer categoryId = Integer.parseInt(id);
            List<FNewsDTO> showList = fNewsService.queryNewsList(categoryId);
            if("1".equals(site)){
                for(FNewsDTO dto : showList){
                    // 把标题"青岛市"更换成"山东省"
                    String title = dto.getTitle();
                    title = title.replace("青岛市", "山东省");
                    dto.setTitle(title);
                }
            }
            request.setAttribute("newsList", showList);
        }
        return url;
    }

    /**
     * 注册提交
     * @return
     */
    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> reg(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        Session session = SecurityUtils.getSubject().getSession();
        // 获取openId
        String openId = "000adf";
        String backUrl = request.getParameter("backUrl");
        // todo
        String userName = (String)params.get("userName");
        String idCard = (String)params.get("idCard");
        String company = (String)params.get("company");
        String sex = (String)params.get("sex");
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(idCard)) {
            return new Result<String>().error("姓名和身份证号不能为空");
        }
        //校验身份证号不能重复
        TUserEntity dto = tUserService.getUserByIdCard(idCard);
        if(dto != null) {
            //return new Result<String>().error("身份证号已经注册");
            session.setAttribute(GlobalConstant.SESSION_USER, dto);
            return new Result<String>().error(201, backUrl);
        }
        dto = new TUserEntity();
        dto.setOpenid(openId);
        dto.setRealName(userName);
        dto.setIdCard(idCard);
        dto.setSex(sex);
        dto.setCompany(company);
        dto.setCreateDate(new Date());
        tUserService.insert(dto);
        session.setAttribute(GlobalConstant.SESSION_USER, dto);
        return new Result<String>().ok(backUrl);
    }

    /**
     * 报名
     * @param dto
     * @return
     */
    @RequestMapping(value = "/subSignup")
    @ResponseBody
    public Result<String> signup(TSignupRecordDTO dto) {
        TSignupRecordEntity entity = tSignupRecordService.queryIfExist(dto);
        if (entity != null) {
            return new Result<String>().error("请勿重复报名");
        }
        dto.setSignupDate(new Date());
        tSignupRecordService.save(dto);
        return new Result<String>().ok("报名成功");
    }

    /**
     * 题库列表
     * @param params
     * @param request
     * @return
     */
    @RequestMapping(value = "/exam-list", method = RequestMethod.GET)
    public String examsPage(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletRequest request) {
        PageData<TQuestionDTO> page = tQuestionService.page(params);
        List<TQuestionDTO> list = page.getList();
        for(TQuestionDTO dto : list) {
            HashMap map = MapUtil.newHashMap();
            dto.setQuestionItemList(tQuestionItemService.list(map));
        }
        request.setAttribute("list", page.getList());
        return "exam-list";
    }

    @RequestMapping(value = "/exam/{id}", method = RequestMethod.GET)
    public String exams(@PathVariable("id") String id, HttpServletRequest request) {
        Session session = SecurityUtils.getSubject().getSession();
        System.out.println(session.getTimeout());
        TUserEntity userEntity = (TUserEntity)session.getAttribute(GlobalConstant.SESSION_USER);
        if(userEntity == null) {
            request.setAttribute("backUrl", "/h5/exam/" + id);
            return "login";
        }

        HashMap param = MapUtil.newHashMap();
        param.put("question_id", id);
        List<TQuestionItemDTO> list = tQuestionItemService.list(param);
        for(TQuestionItemDTO dto : list) {
            HashMap map = MapUtil.newHashMap();
            map.put("item_id", dto.getId());
            dto.setOptionsDTOList(tQuestionOptionsService.list(map));
        }
        request.setAttribute("id",id);
        request.setAttribute("exam", list);
        return "exam";
    }

    // 证书查询
    @RequestMapping(value = "/queryCer", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> query(TSignupRecordDTO dto) {
        // 验证身份证号和姓名不能为空
        if(StringUtils.isEmpty(dto.getIdCard()) || StringUtils.isEmpty(dto.getUserName())) {
            return new Result<String>().error("姓名和身份证号不能为空");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("idCard", dto.getIdCard());
        params.put("userName", dto.getUserName());
        List<TSignupRecordDTO> list = tSignupRecordService.list(params);
        if(list != null && list.size() > 0) {
            //TSignupRecordDTO  list.get(0);
            return new Result<String>().ok("查询成功");
        }
        return new Result<String>().error("未查到信息");
    }

    // 运动员证查询
    @RequestMapping(value = "/queryAthlete", method = RequestMethod.GET)
    @ResponseBody
    public Result<FAthleteDTO> queryAthlete(FAthleteDTO dto) {
        // 验证身份证号和姓名不能为空
        if(StringUtils.isEmpty(dto.getIdCard()) || StringUtils.isEmpty(dto.getUsername())) {
            return new Result<FAthleteDTO>().error("姓名和身份证号不能为空");
        }
        Map params = new HashMap();
        params.put("idCard", dto.getIdCard());
        params.put("username", dto.getUsername());
        List<FAthleteDTO> list = fAthleteService.list(params);
        if(list != null && list.size() > 0) {
            FAthleteDTO fAthleteDTO =  list.get(0);
            return new Result<FAthleteDTO>().ok(fAthleteDTO);
        }
        return new Result<FAthleteDTO>().error("未查到信息");
    }

    // 根据ID查询运动员证件
    @RequestMapping(value = "/queryAthleteById", method = RequestMethod.GET)
    @ResponseBody
    public Result<FAthleteEntity> queryAthleteById(FAthleteDTO dto) {
        FAthleteEntity entity = fAthleteService.selectById(dto.getId());

        //根据身份证号查询考级信息1和比赛成绩2
        List<FCertificateDTO> certList = fCertificateService.queryByIdCardAndType(entity.getIdCard(),1);
        entity.setCertList(certList);
        List<FCertificateDTO> scoreList = fCertificateService.queryByIdCardAndType(entity.getIdCard(), 2);
        entity.setScoreList(scoreList);

        if(entity != null) {
            Date date = entity.getExpirationDate();
            String expirationDate = DateUtils.format(date, "yyyy-MM-dd");
            entity.setExpirationDateStr(expirationDate);
            return new Result<FAthleteEntity>().ok(entity);
        }

        return new Result<FAthleteEntity>().error("未查到信息");
    }

    @RequestMapping(value = "/news/{id}", method = RequestMethod.GET)
    public String news(@PathVariable("id") String id, HttpServletRequest request) {
        FNewsEntity news = fNewsService.selectById(id);
        if (news == null) {
            return "404";
        }
        request.setAttribute("news", news);
        return "news";
    }

    /**
     * 图片上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result<Map<String, String>> tinymceUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new Result<Map<String, String>>().error("上传文件不能为空");
        }
        //上传文件
        String fileName = new Date().getTime() + "";
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String path = picDir + fileName + "." + extension;
        file.transferTo(new File(path));

        Map<String, String> data = new HashMap<>(1);
        data.put("location", domain + fileName + "." + extension);
        return new Result<Map<String, String>>().ok(data);
    }

    @RequestMapping(value = "/submitAnswer", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> submitAnswer(@RequestParam Map<String, Object> params) {
        Session session = SecurityUtils.getSubject().getSession();
        System.out.println(session.getTimeout());
        TUserEntity wxUser = (TUserEntity) session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if (wxUser == null) {
            return new Result<String>().error(401, "请先登录");
        }
        String openId = wxUser.getOpenid();
        TUserEntity userEntity = tUserService.getUserByOpenId(openId);
        if (userEntity == null) {
            return new Result<String>().error("请先注册");
        }
        String id = (String) params.get("id");
        String answers = (String) params.get("answers");
        System.out.println("answers=" + answers);
        // string字符串转json对象
        JSONArray jsonArray = JSONArray.parseArray(answers);
        // json对象转java对象
        List<Map> list = jsonArray.toJavaList(Map.class);
        // answer-1-2  answer-题目id-选项id
        // [{"key":"answer-1-2","val":"2"}]
        Map answerMap = tQuestionItemService.rebuildAnswer(answers);
        tQuestionItemService.submitAnswer(id, answerMap, userEntity.getId().intValue());
        return new Result<String>().ok("答题完成");
    }

    /**
     * 根据分类查看文章列表
     */
    @GetMapping("queryNewsList/{categoryId}")
    public Result<List<FNewsDTO>> queryNewsList(@PathVariable Long categoryId){

        List<FNewsDTO> list = fNewsService.getCoachByType(categoryId.intValue());

        return new Result<List<FNewsDTO>>().ok(list);
    }

    /**
     * 查文章详情
     */
    @GetMapping("queryNewsById/{id}")
    public Result<FNewsEntity> queryNewsById(@PathVariable("id") Long id) {
        FNewsEntity data = fNewsService.selectById(id);

        return new Result<FNewsEntity>().ok(data);
    }

    /**
     * 证书查询
     */
    @RequestMapping(value = "/cer-detail", method = RequestMethod.GET)
    public String queryCertification(@RequestParam Map<String,Object> params, HttpServletRequest request){
        List<TCertificateDTO> list = tCertificateService.queryListByNameAndIDCard(params);
        if(list == null || list.size() == 0){
            return "redirect:/h5/nodata";
        }
        request.setAttribute("list",list);
        return "cer-detail";
    }

    /**
     * 查询专家列表
     */
    @ResponseBody
    @GetMapping("queryExpertList/{id}")
    public Result<List<FNewsDTO>> queryExpertList(@PathVariable Long id){
        List<FNewsDTO> list = fNewsService.getCoachByType(id.intValue());
        return new Result<List<FNewsDTO>>().ok(list);
    }

    /**
     * 查询专家详情
     */
    @ResponseBody
    @GetMapping("queryExpertInfo/{id}")
    public Result<FNewsEntity> queryExpertInfo(@PathVariable Long id){

        FNewsEntity tNewsDTO = fNewsService.selectById(id);

        return new Result<FNewsEntity>().ok(tNewsDTO);

    }
//    **********************************************

    /**
     * 查询新闻中心分类
     */
    @ResponseBody
    @GetMapping("getNewsClassify/{type}")
    public Result<List<FClassifyDTO>> getNesClassify(@PathVariable Integer type){
        List<FClassifyDTO> list = fClassifyService.queryByType(type);
        return new Result<List<FClassifyDTO>>().ok(list);

    }

    /**
     * 根据分类和类型查询新闻详情
     */
    @ResponseBody
    @GetMapping("getNewsByType/{classId}/{type}")
    public Result<List<FNewsDTO>> getNewsByType(@PathVariable Integer classId, @PathVariable Integer type){
        List<FNewsDTO> list = fNewsService.getNewsByType(classId,type);
        return new Result<List<FNewsDTO>>().ok(list);
    }
    /**
     * 查询会员单位
     */
    @ResponseBody
    @GetMapping("getMemberUnit")
    public Result getMemberUnit(@RequestParam Map<String,Object> params){
        List<FMemberUnitDTO> list = fMemberUnitService.queryList();
        return new Result<List<FMemberUnitDTO>>().ok(list);
    }
    /**
     * 查询教练列表
     */
    @ResponseBody
    @GetMapping("getCoachList/{type}")
    public Result getCoachList(@PathVariable Integer type){
        List<FNewsDTO> list = fNewsService.getCoachByType(type);
        return new Result<List<FNewsDTO>>().ok(list);
    }

    /**
     * 获取会员单位列表
     * @param
     * @return
     */
    @ResponseBody
    @GetMapping("getMemberList")
    public Result getMemberList(){

        List<FClubDTO> list = clubService.quryClubList();

        return new Result<List<FClubDTO>>().ok(list);
    }

    /**
     * 根据身份证和姓名查询
     * @param params
     * @return
     */

    @ResponseBody
    @GetMapping("queryScore")
    public Result queryInfo(@RequestParam Map<String,Object> params) {
        String name = (String)params.get("name");
        String idCard = (String)params.get("idCard");
        if(StringUtils.isBlank(name) || StringUtils.isBlank(idCard)){
            return new Result().error("参数错误，请重新输入");
        }

        FCertificateDTO fCertificateDTO = fCertificateService.queryScore(params);
        if(fCertificateDTO != null) {
            return new Result<FCertificateDTO>().ok(fCertificateDTO);
        }else{
            return new Result().error("查不到该学生");
        }
    }

    /**
     * 根据id和考试类型查询
     * @param id
     * @return
     */

    @ResponseBody
    @GetMapping("queryById/{id}")
    public Result queryById(@PathVariable String id) {
        List<FCertificateEntity>  list = fCertificateService.getByIdCard(id, "1");
        return new Result<List<FCertificateEntity>>().ok(list);
    }
    /**
     * 查询俱乐部
     */
    @ResponseBody
    @GetMapping("/queryClubList")
    public Result<List<FClubDTO>> quryClubList(){
        List<FClubDTO> list = clubService.quryClubList();
        return new Result<List<FClubDTO>>().ok(list);
    }


    /**
     * 会员单位在线申请
     * @return
     */
    @RequestMapping(value = "/applySubmit", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> apply(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        Session session = SecurityUtils.getSubject().getSession();
        // 获取openId
        String openId = "000adf";
        String backUrl = request.getParameter("backUrl");
        // todo
        String userName = (String)params.get("userName");
        String idCard = (String)params.get("idCard");
        String company = (String)params.get("company");
        String sex = (String)params.get("sex");
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(idCard)) {
            return new Result<String>().error("姓名和身份证号不能为空");
        }
        //校验身份证号不能重复
        TUserEntity dto = tUserService.getUserByIdCard(idCard);
        if(dto != null) {
            //return new Result<String>().error("身份证号已经注册");
            session.setAttribute(GlobalConstant.SESSION_USER, dto);
            return new Result<String>().error(201, backUrl);
        }
        dto = new TUserEntity();
        dto.setOpenid(openId);
        dto.setRealName(userName);
        dto.setIdCard(idCard);
        dto.setSex(sex);
        dto.setCompany(company);
        dto.setCreateDate(new Date());
        tUserService.insert(dto);
        session.setAttribute(GlobalConstant.SESSION_USER, dto);
        return new Result<String>().ok(backUrl);
    }



}
